package com.wsc.personalblog.service.impl;

import com.wsc.personalblog.entity.Category;
import com.wsc.personalblog.entity.CategoryExample;
import com.wsc.personalblog.mapper.CategoryMapper;
import com.wsc.personalblog.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 获取到分类信息
     * @return
     */
    @Override
    public List<Category> getCategoryInfo() {
        List<Category> categoryList = categoryMapper.selectByExample(null);
        return categoryList;
    }

    @Override
    public void deleteCategory(Integer id) {
        try{
            categoryMapper.deleteByPrimaryKey(id);
        }catch (Exception e){
            throw new RuntimeException("删除分类失败，该分类下还有文章");
        }

    }

    @Override
    public List<Category> getCategoryInfoByName(String name) {
        if(name == null || name.length() == 0){
            List<Category> categoryList = categoryMapper.selectByExample(null);
            return categoryList;
        }
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        criteria.andNameLike("%"+name+"%");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        return categoryList;
    }

    /**
     * 添加分类
     * 参数：名称name(必须)、描述description(非必须)
     * @param category
     * @return
     */
    @Override
    public Integer addCategory(Category category) {
        String name = category.getName();
        if(name == null || name.trim().length() == 0)
            throw new RuntimeException("请输入正确的名称");
        String description = category.getDescription();
        if(description == null || description.trim().length() == 0)
            category.setDescription(null);
        category.setCreateDate(LocalDateTime.now());
        try {
            categoryMapper.insertSelective(category);
            return category.getId();
        }catch (Exception e){
            throw new RuntimeException("添加分类失败，分类名称已有");
        }
    }

    /**
     * 更新分类描述信息根据分类id
     * @param category 分类信息
     * @return
     */
    @Override
    public void updateCategoryDescription(Category category) {
        String description = category.getDescription();
        String name = category.getName();
        if(((name == null || name.trim().length() == 0) && (description == null || description.trim().length() == 0))
                || (category.getId() == null ||category.getId() == 0))
            throw new RuntimeException("请输入正确的描述信息");
        try{
            categoryMapper.updateByPrimaryKeySelective(category);
        }catch (Exception e){
            throw new RuntimeException("更新分类信息失败，分类名称已有");
        }
    }


}
